package com.coinworld.admin.handler;

import com.coinworld.exception.BusinessException;
import com.coinworld.response.ResponseCode;
import com.coinworld.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
        Result result = new Result();
        if (ex instanceof BusinessException) {
            BusinessException be = (BusinessException) ex;
            result.setCode(be.getCode().getCode());
            result.setMsg(be.getMessage());
            log.error(result.getMsg() + "[" + result.getCode() + "]");
            return new ResponseEntity<>(result, HttpStatus.OK);
        }  else {
            HttpStatus status = getStatus(request);
            result.setCode(ResponseCode.Common.FAILURE.getCode());
            result.setMsg(ResponseCode.Common.FAILURE.getMsg());
            log.error(ResponseCode.Common.FAILURE.getMsg(), ex);
            return new ResponseEntity<>(result, status);
        }
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }

}